<?php

/**
 * File processing
 * @author Fan
 */
Yii::import('ext.wideImage.WideImage');

class DComImgMan extends CModel {

    public $fileName;
    public $errorMsg;
    private $_fileInfo;
    private $_myParam;

    public function __construct() {
        $this->_myParam = array(
            'upload_dir' => Yii::app()->params['newsletter_dir'],
            'thumb_dir'  => Yii::app()->params['newsletter_thumb_dir'],
            'upload_url' => Yii::app()->params['newsletter_url'],
            'thumb_url'  => Yii::app()->params['newsletter_thumb_dir'],
            'image'      => Yii::app()->params['newsletter_image'],
        );
    }

    public function attributeNames() {
        return array('fileName');
    }

    public function rules() {
        return array(
            array('fileName', 'validateFile'),
        );
    }

    public function validateFile($attribute, $params) {
        $fileObj = CUploadedFile::getInstanceByName($this->$attribute);

        if ($fileObj) {
            $filePath = $this->_myParam['upload_dir'] . $fileObj->getName();

            //rename if exists
            $newName = $this->getUniqueName($filePath);
            if ($newName != $fileObj->getName()) {
                $filePath        = $this->_myParam['upload_dir'] . $newName;
            }
            $this->_fileInfo = pathinfo($filePath);

            if ($fileObj->saveAs($filePath)) {
                $this->processImage($filePath);
            } else {
                $this->addError($attribute, 'Can not save.');
            }

            return TRUE;
        } else {
            $this->addError($attribute, $fileObj->getError());
            return FALSE;
        }
    }

    /**
     * Resize image & create thumbnail
     */
    private function processImage($filePath) {
        $params   = $this->_myParam['image'];
        $thumbDir = $this->_myParam['thumb_dir'];

        //resize
        $imageObj = WideImage::load($filePath);
        $imageObj->resizeDown($params['max_width'], $params['max_height'])
            ->saveToFile($filePath);

        //create thumbnail
        $thumbPath = $thumbDir . $this->_fileInfo['basename'];
        $imageObj->resizeDown($params['thumb_width'], $params['thumb_height'])
            ->saveToFile($thumbPath);
        unset($imageObj);

        //create fixed thumbnail
        $thumbObj = WideImage::load($thumbPath);
        $path     = $thumbDir . rtrim($this->_fileInfo['filename'], '_')
            . '_fix.' . $this->_fileInfo['extension'];
        $bgColor  = $thumbObj->allocateColor(
            $params['thumb_bg']['0'], $params['thumb_bg']['1'], $params['thumb_bg']['2']
        );
        $thumbObj->resizeCanvas($params['thumb_width'], $params['thumb_height'], 'center', 'center', $bgColor)
            ->saveToFile($path);

        return TRUE;
    }

    /**
     * Calculate the unique image name
     * @param string $filePath the original name
     * @param string the new name
     */
    private function getUniqueName($filePath) {
        $pathInfo  = pathinfo($filePath);
        $fileName  = $pathInfo['basename'];
        $fileExist = file_exists($filePath);
        $count     = 1;

        while ($fileExist) {
            $fileName  = rtrim($pathInfo['filename'], '_')
                . '_' . $count . '.' . $pathInfo['extension'];
            $newPath   = $pathInfo['dirname'] . '/' . $fileName;
            $fileExist = file_exists($newPath);
            $count++;
        }

        return $fileName;
    }

    /**
     * Get url files
     * @param type $dir
     * @return array with format 
     *  array(
     *      'name'=>'',
     *      'url'=>'',
     *      'thumb'=>'',
     *  )
     */
    public function getFiles($dir) {
        $result = array();
        $fileList     = scandir($dir);
        $uploadDir    = $this->_myParam['upload_dir'];
        $baseUrl      = Yii::app()->baseUrl . $this->_myParam['upload_url'];
        $baseThumbUrl = Yii::app()->baseUrl . $this->_myParam['thumb_url'];

        foreach ($fileList as $fileName) {
            $firstChar = substr($fileName, 0, 1);
            $filePath  = $uploadDir . $fileName;

            if (($firstChar != '.') && (is_file($filePath))) {
                $pathInfo = pathinfo($filePath);

                $aTemp = array(
                    'name'      => $fileName,
                    'url'       => $baseUrl . $fileName,
                    'thumb'     => $baseThumbUrl . $fileName,
                    'thumb_fix' => $baseThumbUrl . $pathInfo['filename']
                    . '_fix.' . $pathInfo['extension'],
                );
                array_push($result, $aTemp);
            }
        }

        return $result;
    }

    public function deleteFile($fileName) {
        $aDelFile = array();

        //file
        $filePath = $this->_myParam['upload_dir'] . $fileName;
        $pathInfo = pathinfo($filePath);
        array_push($aDelFile, $filePath);

        //thumb
        $filePath = $this->_myParam['thumb_dir'] . $fileName;
        array_push($aDelFile, $filePath);

        $filePath = $this->_myParam['thumb_dir'] . rtrim($pathInfo['filename'], '_')
            . '_fix.' . $pathInfo['extension'];
        array_push($aDelFile, $filePath);

        foreach ($aDelFile as $file) {
            if (is_file($file)) {
                unlink($file);
            } else {
                $this->errorMsg = 'File ' . $file . ' does not exist';
                return FALSE;
            }
        }
        return TRUE;
    }

}